using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace SolutionFactory.Services
{
    public class RemoveTFSBindingsVisitor : IFileVisitor
    {
        private readonly ILogger _logger;
        private readonly IList<IFileVisitor> _internalVisitors;

        public RemoveTFSBindingsVisitor(ILogger logger)
        {
            _logger = logger;
            _internalVisitors = new List<IFileVisitor>
                                    {
                                        new DeleteFileVisitor(".vspscc"),
                                        new DeleteFileVisitor(".vssscc"),
                                        new DynamicFileVisitor(".csproj", ProjModifier)
                                    };
        }
       
        private void ProjModifier(FileInfo fileInfo)
        {
             string projContents = File.ReadAllText(fileInfo.FullName);
            
            string[] sourceControlSectionPatterns = new[]
                {
                    @"<SccProjectName>\w+?</SccProjectName>",
                    @"<SccLocalPath>\w+</SccLocalPath>",
                    @"<SccAuxPath>\w+?</SccAuxPath>",
                    @"<SccProvider>\w+?</SccProvider>"
                };

            string newProjContents = projContents;
            foreach(var pattern in sourceControlSectionPatterns)
            {
                newProjContents = Regex.Replace(newProjContents, pattern, "");
            }

            if (projContents != newProjContents)
            {
                _logger.Log(string.Format("Found some source control section in {0}.  Removing....", fileInfo.Name));
                File.WriteAllText(fileInfo.FullName, newProjContents);
            }
         
        }

        public void Visit(FileInfo file)
        {
            foreach (var fileVisitor in _internalVisitors)
            {
                fileVisitor.Visit(file);

                //no need to continue if the file was deleted
                if(!file.Exists)
                    break;
            }
        }
    }
}